
package com.borqs.music.tasks;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.borqs.music.executor.Task;
import com.borqs.music.executor.TaskListener;
import com.borqs.music.http.HttpResponse;
import com.borqs.music.model.SongInfo;

public abstract class SongTask extends Task {
    public static final int PAGE_COUNT = 20;

    private boolean isFullInfo = false;

    public SongTask(TaskListener listener, boolean isFullInfo) {
        super(listener);
        this.isFullInfo = isFullInfo;
    }

    protected boolean isFull(){
        return isFullInfo;
    }

    @Override
    public Object handleResponse(HttpResponse resp) throws Exception {
        checkResponse(resp);
        JSONArray jArr = resp.asJSONArray();
        List<SongInfo> songs = decodeSongsJSONArray(jArr);
        return songs;
    }

    protected List<SongInfo> decodeSongsJSONArray(JSONArray jArr) throws JSONException {
        List<SongInfo> songs = new ArrayList<SongInfo>(10);
        for (int i = 0, len = jArr.length(); i < len; i++) {
            JSONObject jObj;
            jObj = jArr.getJSONObject(i);
            SongInfo song = new SongInfo();
            song.id = jObj.getInt("song_id");
            song.title = jObj.getString("title");
            song.artist = jObj.getString("singer_name");
            song.fileMd5 = jObj.getString("file_md5");
            song.fileUrl = jObj.getString("file_url");
            song.album = jObj.getString("album");
            song.duration = jObj.getInt("duration");
            song.fileType = jObj.getString("file_type");
            song.bitrate = jObj.getInt("bitrate");
            song.fileSize = jObj.getLong("file_size");
            song.imgUrl = jObj.getString("img_url");
            song.fileName = jObj.getString("file_name");
            song.isFavorite = (jObj.optInt("isfavor", 0)==1);
            song.isNotInDevice = true;
            song.isPublicSong = (jObj.optInt("publish_state", 2) == 2);
            if (isFullInfo) {
                song.lyrics =  jObj.getString("lyric");
                // song.downloadCount = jObj.getString("download_count");
                // song.fileMd5 = jObj.getString("file_md5");
                // song.style = jObj.getString("style");
                // song.tag = jObj.getString("tag");
                // song.description = jObj.getString("description");
                // song.favorCount = jObj.getString("favor_count");
                // song.listenCount = jObj.getString("listen_count");
                // song.likeCount = jObj.getString("like_count");
                // song.createdTime = jObj.getString("created_time");
                // song.destroyedTime = jObj.getString("destroyed_time");
            }

            songs.add(song);
        }

        return songs;
    }
}
